package hamaster.jpbc.crypt.aes;

import hamaster.jpbc.exception.CryptException;
import hamaster.jpbc.pbc.PBCDriver;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class MySQLAESCrypt {

	private String key;

	public MySQLAESCrypt(String key) {
		this.key = key;
	}

	public String encrypt(String plain) throws CryptException {
		try {
			byte[] data = plain.getBytes("UTF-8");
			return PBCDriver.hex(crypt(data, key, Cipher.ENCRYPT_MODE));
		} catch (UnsupportedEncodingException e) {
		} catch (BadPaddingException e) {
			throw new CryptException(e);
		}
		return null;
	}

	public String decrypt(String cipher) throws CryptException {
		try {
			byte[] data = PBCDriver.unhex(cipher);
			return new String(crypt(data, key, Cipher.DECRYPT_MODE));
		} catch (UnsupportedEncodingException e) {
		} catch (BadPaddingException e) {
			throw new CryptException(e);
		}
		return null;
	}

	private byte[] crypt(byte[] data, String key, int opmode) throws UnsupportedEncodingException, BadPaddingException {
		try {
	        byte[] keyBytes = Arrays.copyOf(key.getBytes("ASCII"), 16);
	        SecretKey sk = new SecretKeySpec(keyBytes, "AES");
	        Cipher cipher = Cipher.getInstance("AES");
	        cipher.init(opmode, sk);
	        return cipher.doFinal(data);
	    } catch (NoSuchAlgorithmException e) {
	    } catch (NoSuchPaddingException e) {
	    } catch (InvalidKeyException e) {
	    } catch (IllegalBlockSizeException e) {
	    }
	    return null;
	}
}
